﻿#region Licence
// <copyright file="Core/SysUtilisateurViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System.Collections.Generic;
using System.Linq;
using Core.Class;
using Core.Enums;
using Database.POCO;
using GalaSoft.MvvmLight.CommandWpf;
using Helpers;
using Helpers.Class;
using Interfaces.Enums;

#endregion

namespace Core.ViewModel.Controls
{
    /// <summary>
    /// 
    /// </summary>
    public class SysUtilisateurViewModel : ViewModelBaseModule
    {
        #region fields

        private bool _isPasswordChanged;

        #endregion
        
        #region properties

        /// <summary>
        /// 
        /// </summary>
        private SysUtilisateur _user;
        public SysUtilisateur User
        {
            get { return _user; }
            set
            {
                _user = value;
                RaisePropertyChanged(() => User);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private string _password;
        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                _isPasswordChanged = true;
                RaisePropertyChanged(() => Password);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private List<RightsParameter> _droitsUser;
        public List<RightsParameter> DroitsUser
        {
            get { return _droitsUser; }
            set
            {
                _droitsUser = value;
                RaisePropertyChanged(() => DroitsUser);
            }
        }

        public RelayCommand CloseCommand { get; set; }
        public RelayCommand SaveCommand { get; set; }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        public SysUtilisateurViewModel(SysUtilisateur user)
        {
            User = user;

            LoadRights();
            SaveCommand = new RelayCommand(Save, CanSave);
            CloseCommand = new RelayCommand(Close);
        }

        /// <summary>
        /// 
        /// </summary>
        public SysUtilisateurViewModel() : this(new SysUtilisateur())
        {}

        #region private

        /// <summary>
        /// Chargement des droits
        /// </summary>
        private void LoadRights()
        {
            if (Services.AccessControlService.IsAuthorizedFunction(Services.RightsService.GetIdentifiantRight((int)RightsEnum.ViewParametersSystem, TypeModulesEnum.Core)))
            {
                DroitsUser = new List<RightsParameter>();
                var droits = Services.DatabaseService.Service.GetAll<SysDroits>().ToList();

                //On charge les droits actuels de l'utilisateur
                var userRights = Services.DatabaseService.Service.Where<SysUtilisateurDroitFonction>(d => d.Utilisateur.ID == User.ID);

                if (droits.Any())
                {
                    foreach (var paramsGroup in droits.GroupBy(p => p.Module))
                    {
                        var newDroit = new RightsParameter
                        {
                            Header = ModulesHelper.LocalizeModule((TypeModulesEnum)paramsGroup.Key),
                            Droits = new List<RightsValue>()
                        };

                        foreach (var droit in paramsGroup)
                        {
                            var valeurDroit = 0;
                            if (userRights.Any())
                            {
                                SysDroits droit1 = droit;
                                var rights = userRights.Where(d => d.Droit.ID == droit1.ID);
                                if (rights.Any())
                                {
                                    valeurDroit = rights.First().Value;
                                }
                            }
                            newDroit.Droits.Add(new RightsValue { Droit = droit, DroitFonction = new SysUtilisateurDroitFonction { Value = 0, Utilisateur = User, Droit = droit}, ValueTemp = valeurDroit});
                            newDroit.Droits = newDroit.Droits.OrderBy(d => d.Droit.LibelleDroit).ToList();
                        }
                        DroitsUser.Add(newDroit);
                    }
                }
            }
        }

        #endregion

        #region RelayCommand

        private void Save()
        {
            //1. Génération d'un mot de passe crypté avec un nouveau GDS pour l'utilisateur
            if (_isPasswordChanged)
            {
                Services.AccessControlService.CreateNewPasswordForUser(User, Password);
            }
            Services.DatabaseService.Service.Save<SysUtilisateur>(User);

            //2. On supprime tous les droits de cet utilisateur
            Services.DatabaseService.Service.Delete<SysUtilisateurDroitFonction>(d => d.Utilisateur.ID == User.ID);

            //3. Enregistrement des droits de l'utilisateur
            foreach (var rightsParameter in DroitsUser)
            {
                foreach (var droitFonction in rightsParameter.Droits)
                {
                    if (droitFonction.ValueTemp != 0)
                    {
                        droitFonction.DroitFonction.Value = droitFonction.ValueTemp;
                        Services.DatabaseService.Service.Save<SysUtilisateurDroitFonction>(droitFonction.DroitFonction);    
                    }
                }
            }
            CallBackConfirmed();
            CloseAction();
            
        }

        private bool CanSave()
        {
            return !string.IsNullOrEmpty(User.Code);
        }

        private void Close()
        {
            CloseAction();
        }

        #endregion
    }
}
